<template>
  <div>
    <el-card class="box-card">
      <el-form ref="form" inline>
        <el-form-item
          ><el-input placeholder="用户名" v-model="keyword"></el-input
        ></el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="getUserList"
          >查询</el-button
        >
        <el-button @click="clearKeyword">清空</el-button>
      </el-form>

      <el-form :inline="true" size="small">
        <el-form-item>
          <el-button type="primary" @click="isDialogShow = true"
            >添加</el-button
          >
          <el-button
            type="danger"
            @click="deleteAll"
            :disabled="!selectedUser.length"
            >批量删除</el-button
          >
        </el-form-item>
      </el-form>

      <el-table
        :data="userList"
        v-loading="loading"
        border
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column type="index" label="序号" width="80" align="center">
        </el-table-column>
        <el-table-column label="用户名" width="150" prop="username">
        </el-table-column>
        <el-table-column label="用户昵称" prop="nickName"> </el-table-column>
        <el-table-column label="角色列表" width="200" prop="roleName">
        </el-table-column>
        <el-table-column label="创建时间" width="180" prop="gmtCreate">
        </el-table-column>
        <el-table-column label="更新时间" width="180" prop="gmtModified">
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template v-slot="{ row }">
            <el-button
              type="info"
              size="small"
              icon="el-icon-user-solid"
              @click="getRoleInfo(row.id, row.username)"
            ></el-button>
            <el-button
              type="primary"
              size="small"
              icon="el-icon-edit-outline"
              @click="editUser(row)"
            ></el-button>
            <el-button
              type="danger"
              size="small"
              icon="el-icon-delete"
              @click="deleteUser(row.id)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        :current-page.sync="currentPage"
        :page-sizes="[5, 10, 15, 20]"
        :page-size.sync="pageSize"
        layout=" prev, pager, next, sizes,total"
        :total="totalNum"
        background
      >
      </el-pagination>
    </el-card>

    <!-- 新增添加弹窗 -->
    <el-dialog
      title="添加用户"
      :visible.sync="isDialogShow"
      width="50%"
      @close="resetForm"
    >
      <el-form
        :model="form"
        ref="form"
        :rules="rules"
        label-width="80px"
        :inline="false"
        size="normal"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="用户昵称">
          <el-input v-model="form.nickName"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password">
          <el-input v-model="form.password"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer">
        <el-button @click="resetForm">取消</el-button>
        <el-button type="primary" @click="addOrUpdateUser">确定</el-button>
      </span>
    </el-dialog>

    <!-- 修改角色弹窗 -->
    <el-dialog
      title="设置角色"
      :visible.sync="isRoleDialogShow"
      width="50%"
      @close="resetRoleInfo"
    >
      <el-form label-width="80px" :inline="false" size="normal">
        <el-form-item label="用户名">
          <el-input v-model="roleInfo.username"></el-input>
        </el-form-item>
        <el-form-item label="角色列表">
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll"
            >全选</el-checkbox
          >
          <div style="margin: 15px 0;"></div>
          <el-checkbox-group v-model="roleInfo.checkedList">
            <el-checkbox
              v-for="item in roleInfo.allRolesList"
              :label="item.id"
              :key="item.id"
              >{{ item.roleName }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
      </el-form>

      <span slot="footer">
        <el-button @click="resetRoleInfo">取消</el-button>
        <el-button type="primary" @click="setUserRole">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  reqUserList,
  reqUserListByPage,
  reqAddUser,
  reqUpdateUser,
  reqDeleteAll,
  reqDeleteUser,
  reqUserRoleInfo,
  reqSetRole
} from "@/api/user";
export default {
  name: "User",
  data() {
    return {
      loading: false,
      currentPage: 1, // 当前页码
      pageSize: 5, //当前页码展示条数
      totalNum: 0, //当前数据总条数
      keyword: "", //当前查询框输入内容
      userList: [],
      isDialogShow: false,
      form: {
        username: "",
        password: "",
        nickName: ""
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 5, max: 16, message: "长度在 5 到 16 个字符", trigger: "blur" }
        ]
      },
      selectedUser: [],
      isRoleDialogShow: false,
      roleInfo: {
        allRolesList: [],
        checkedList: [],
        id: "",
        username: ""
      }
    };
  },

  methods: {
    //发送请求后更新数据(获取分页数据)
    async getUserList() {
      this.loading = true;
      const re = await reqUserListByPage(
        this.currentPage,
        this.pageSize,
        this.keyword
      );
      // console.log(re.data);
      this.totalNum = re.data.total;
      this.userList = re.data.items;
      this.selectedUser = [];
      this.loading = false;
    },

    // 清空查询关键字
    clearKeyword() {
      this.keyword = "";
      this.getUserList();
    },

    //关闭弹窗
    resetForm() {
      this.isDialogShow = false;
      this.form = {
        username: "",
        password: "",
        nickName: ""
      };
      this.$refs.form.clearValidate();
    },

    //新增或修改用户(新增直接携带数据发送请求到服务器即可,如果是修改则需要判断是否有ID存在,因为ID是服务端自动分配的)
    addOrUpdateUser() {
      this.$refs.form.validate(async v => {
        if (v) {
          // 如果有ID存在的情况下说明是修改,携带最新的form对象去更新服务端数据
          if (this.form.id) await reqUpdateUser(this.form);
          // 否则是新增,直接拿着新的form表单去新增服务端数据即可
          else await reqAddUser(this.form);
          // 无论是修改还是新增,都需要重新获取数据
          await this.getUserList();
          // 请求成功后要重置之前收集好的表单数据并关闭弹窗
          this.resetForm();
        } else {
          this.$message.error("请检查表单输入是否正确");
          return false;
        }
      });
    },

    // 修改用户按钮
    editUser(user) {
      this.form = user;
      this.isDialogShow = true;
    },

    // 多选框回调函数
    handleSelectionChange(val) {
      this.selectedUser = val;
    },

    // 批量删除
    async deleteAll() {
      const idArr = this.selectedUser.map(item => item.id);
      console.log(idArr);
      await reqDeleteAll(idArr);
      this.getUserList();
    },

    // 单个删除
    async deleteUser(id) {
      await reqDeleteUser(id);
      this.getUserList();
    },

    //获取角色信息
    async getRoleInfo(id, username) {
      const { data } = await reqUserRoleInfo(id);
      this.roleInfo.allRolesList = data.allRolesList;
      this.roleInfo.checkedList = data.assignRoles.map(item => item.id);
      this.roleInfo.id = id;
      this.roleInfo.username = username;
      this.isRoleDialogShow = true;
    },

    // 重置角色信息(取消按钮)
    resetRoleInfo() {
      this.roleInfo = {
        allRolesList: [],
        checkedList: [],
        id: "",
        username: ""
      };
      this.isRoleDialogShow = false;
    },

    // 设置角色信息(确定按钮)
    async setUserRole() {
      await reqSetRole(this.roleInfo.id, this.roleInfo.checkedList);
      this.$message.success("分配角色,保存成功");
      this.resetRoleInfo();
      this.getUserList();
    }
  },

  watch: {
    keyword(newval) {
      if (newval === "") this.getUserList();
    },
    currentPage() {
      this.getUserList();
    },
    pageSize() {
      this.getUserList();
    }
  },

  computed: {
    // 是否半选
    isIndeterminate() {
      return (
        this.roleInfo.allRolesList.length > 0 &&
        this.roleInfo.checkedList.length > 0 &&
        this.roleInfo.checkedList.length < this.roleInfo.allRolesList.length
      );
    },
    // 是否全选
    checkAll: {
      get() {
        return (
          this.roleInfo.allRolesList.length > 0 &&
          this.roleInfo.checkedList.length > 0 &&
          this.roleInfo.checkedList.length === this.roleInfo.allRolesList.length
        );
      },
      set(val) {
        if (val)
          this.roleInfo.checkedList = this.roleInfo.allRolesList.map(
            item => item.id
          );
        else this.roleInfo.checkedList = [];
      }
    }
  },

  mounted() {
    // 初始化挂载完毕之后就发送请求
    this.getUserList();
  }
};
</script>

<style scoped>
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}

.box-card {
}
</style>
